package com.custom.custapi.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.custom.custapi.mapper.SuperMapper;
import com.custom.custapi.pojo.SuperBaseEntity;
import com.custom.custapi.pojo.SuperBaseFilter;
import com.custom.custapi.pojo.SuperBasePager;
import com.custom.custapi.pojo.SuperRvId;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author zl
 * @version 1.0
 * @description 服务
 * @date 2025/1/1 1:1
 */
@Slf4j
@Component
public class SuperServiceImpl<T extends SuperBaseEntity> implements SuperService<T> {
    @Resource
    public SuperMapper superMapper;
    protected Class<T> entityClass = currentModelClass();

    protected Class<T> currentModelClass() {
        return (Class<T>) ReflectionKit.getSuperClassGenericType(this.getClass(), SuperServiceImpl.class, 0);
    }

    @Override
    public <R, F extends SuperBaseFilter> SuperBasePager<R> selectPage(F filter) {
        return superMapper.selectPage(filter, entityClass);
    }

    @Override
    public <R> R details(String id, Class<R> rClass) {
        T t = superMapper.selectById(id, entityClass);
        return BeanUtil.copyProperties(t, rClass);
    }

    @Override
    public <R> void update(R r) {
        superMapper.updateById(BeanUtil.copyProperties(r, entityClass));
    }

    @Override
    public <R> void save(R r) {
        superMapper.insert(BeanUtil.copyProperties(r, entityClass));
    }

    @Override
    public <R extends SuperRvId> void saveOrUpdate(R r) {
        if (null == r.getId() || "".equals(r.getId())) {
            save(r);
        } else {
            update(r);
        }
    }
}
